import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Inject, Injectable, InjectionToken } from "@angular/core";
import { Observable, throwError, TimeoutError } from "rxjs";
import { catchError, timeout } from 'rxjs/operators';
export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');
@Injectable()
export class AngularTimeoutInterceptor implements HttpInterceptor {

    constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number) { }
    //://stackoverflow.com/questions/45938931/default-and-specific-request-timeout @author:Michael Ziluck 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const timeoutValue: any = req.headers.get('timeout') || this.defaultTimeout;
        const timeoutValueNumeric: number = Number(timeoutValue);
        return next.handle(req).pipe(timeout(timeoutValueNumeric), catchError((error) => {
            if (error instanceof TimeoutError) {
                return throwError('REST服务请求超时');
            }
            return throwError(error);
        }));
    }
}
